﻿using System;
using System.Globalization;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace Redirection.Layouts.Redirection
{
    public partial class redirectcachemgmt : LayoutsPageBase
    {
        private readonly CacheService _cacheService;
        private RedirectionService _redirectionService;

        public redirectcachemgmt()
        {
            _cacheService = new CacheService(SPContext.Current.Site,HttpContext.Current);
            _redirectionService = new RedirectionService(SPContext.Current.Site, HttpContext.Current);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (Page.IsPostBack) return;
            if (CheckRedirectionEnabled())
            {
                DataBind();
            }
            else
            {
                _pnlDisabled.Visible = true;
                _pnlError.Visible = false;
                _pnlContent.Visible = false;
            }
        }

        private bool CheckRedirectionEnabled()
        {
            return _redirectionService.RedirectionIsActivated;
        }

        protected override void OnDataBinding(EventArgs e)
        {
            _txtCacheExpiration.Text =
                (PropertyBagHelper.LoadValues<int>(SPContext.Current.Web,
                                                   ConstantsService.PropertyBag.RedirectionCacheInterval)/1000).ToString(CultureInfo.CurrentCulture);
            _ltCreationDate.Text =
                PropertyBagHelper.LoadValues<DateTime>(SPContext.Current.Web,
                                                       ConstantsService.PropertyBag.RedirectionCacheCreationKey)
                                 .ToLocalTime()
                                 .ToString(CultureInfo.CurrentCulture);

            if (_cacheService.RedirectionCache != null)
            {
                _grdRedirections.DataSource = _cacheService.RedirectionCache.Select(item => item.Value);
                _grdRedirections.DataBind();

                _ltNumberOfRecords.Text = _cacheService.RedirectionCache.Count.ToString(CultureInfo.CurrentCulture);
            }
            else
            {
                _pnlRecords.Visible = false;
            }
        }

        protected void Save_OnClick(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;

            var cacheInterval = int.Parse(_txtCacheExpiration.Text);

            PropertyBagHelper.SaveValues(SPContext.Current.Web, ConstantsService.PropertyBag.RedirectionCacheInterval,
                                         cacheInterval*1000);
            if (_chkClear.Checked)
            {
                _cacheService.ClearCache();
            }

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["ReturnUrl"]))
            {
                HttpContext.Current.Response.Redirect(HttpContext.Current.Request["ReturnUrl"]);
            }
        }

        protected void Cancel_OnClick(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Redirect(!string.IsNullOrEmpty(HttpContext.Current.Request["ReturnUrl"])
                                                      ? HttpContext.Current.Request["ReturnUrl"]
                                                      : SPUtility.GetServerRelativeUrlFromPrefixedUrl(
                                                          "~site/_layouts/15/settings.aspx"));
        }

        private void CheckPermission()
        {
            if (!SPContext.Current.Web.CurrentUser.IsSiteAdmin)
            {
                Response.StatusCode = 403;
            }
            else
            {
                _pnlContent.Visible = true;
                _pnlError.Visible = false;
            }
        }
    }
}